<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>历史资源监控</title>
    <script src="/js/jquery.js"></script>
    <script src="/js/echarts.js"></script>
</head>
<body>
<!-- 修改时间范围输入框 -->
<div style="margin-top: 20px;">
    <label for="timeRange">历史资源监控>>选择时间范围（分钟）【1-2880】：</label>
    <input type="number" id="timeRange" value="60" min="1" max="2880">
    <button onclick="loadHistoricalData()">刷新数据</button>
</div>
<div style="display: flex; justify-content: space-between; width: 100%; height: 200px;">
    <div id="main_mem" style="flex: 1; min-width: 45%; height: 100%;"></div>
    <div id="main_cpu" style="flex: 1; min-width: 45%; height: 100%;"></div>
</div>
<div style="display: flex; justify-content: space-between; width: 100%; height: 200px;">
    <div id="main_storage" style="flex: 1; min-width: 45%; height: 100%;"></div>
</div>


<script>
    // 定义全局变量
    const charts = [
        {id: 'main_mem', key: 'memUsageRate', name: '内存使用率', data: []},
        {id: 'main_cpu', key: 'cpuUsageRate', name: 'CPU使用率', data: []},
        {id: 'main_storage', key: 'storageUsageRate', name: '存储使用率', data: []}
    ];

    // 初始化执行的代码
    $(document).ready(function () {
        // 初始化图表实例和选项
        initializeCharts();
        // 加载历史数据
        loadHistoricalData();

        // 监听窗口大小变化，调整图表大小
        window.addEventListener('resize', () => {
            charts.forEach(chart => chart.instance.resize());
        });
    });

    // 初始化图表实例和选项
    function initializeCharts() {
        charts.forEach(chart => {
            chart.instance = echarts.init(document.getElementById(chart.id));
            const option = createChartOption(chart.name);
            chart.instance.setOption(option);
        });
    }

    // 修改创建图表选项函数
    function createChartOption(titleText) {
        const timeRange = document.getElementById('timeRange').value; // 获取用户输入的时间范围
        return {
            title: {
                text: `${titleText}，近${timeRange}分钟`, // 动态更新标题
                textStyle: {
                    fontSize: 15
                }
            },
            tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                    params = params[0];
                    const date = new Date(params.value[0]);
                    return [
                        '时间: ' + date.toLocaleString(),
                        '使用率: ' + params.value[1].toFixed(2) + '%'
                    ].join('<br/>');
                }
            },
            xAxis: {
                type: 'time',
                axisLabel: {
                    formatter: value => new Date(value).toLocaleString(),
                    rotate: 35 // 添加此行以竖向展示横坐标文本
                },
                splitLine: {show: false}
            },
            yAxis: {
                type: 'value',
                min: 0,
                max: 100,
                axisLabel: {formatter: '{value} %'}
            },
            series: [{
                name: titleText,
                type: 'line',
                showSymbol: false,
                smooth: true,
                areaStyle: {},
                data: []
            }]
        };
    }

    // 修改加载历史数据函数
    async function loadHistoricalData() {
        const timeRange = document.getElementById('timeRange').value; // 获取用户输入的时间范围
        // 校验timeRange只能在1-2880之间，如果超过这个范围则提示用户重新输入
        if (timeRange < 1 || timeRange > 2880) {
            alert('时间范围必须在1-2880之间');
            // 重置timeRange为60
            document.getElementById('timeRange').value = 60;
            return;
        }
        try {
            const response = await $.ajax({
                url: `/historical?minutes=${timeRange}`, // 将时间范围作为参数传递给后端
                cache: false
            });
            const historicalData = response.data;

            // 处理数据并更新图表
            charts.forEach(chart => {
                chart.data = historicalData.map(item => ({
                    name: Date.parse(item.timestamp),
                    value: [Date.parse(item.timestamp), item[chart.key] * 1]
                }));
                const option = chart.instance.getOption();
                option.title[0].text = `${chart.name}，近${timeRange}分钟`;
                option.series[0].data = chart.data;
                chart.instance.setOption(option);

            });
        } catch (error) {
            console.error('获取历史数据失败:', error);
        }
    }

    // 每隔5秒刷新一次数据
    setInterval(loadHistoricalData, 5000);
</script>
</body>
</html>